from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from itsdangerous import BadData
from . import constants


def generate_save_user_token(openid):
    """对生成的openid进行加密处理"""
    # secret_key 加密字符串, expires_in 生成的token有效时间
    # def __init__(self, secret_key, expires_in=None, **kwargs):
    # 1.创建序列化对象
    serializer = Serializer(settings.SECRET_KEY, constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    # 再进行加密的时候,需要将数据包装成一个字典
    data = {
        "openid": openid
    }
    # 2.调用序列化器的dumps进行加密
    token = serializer.dumps(data)

    return token.decode()


def check_save_user_token(openid):
    """对加密的openid进行解密"""
    # 验证失败，会抛出itsdangerous.BadData异常
    # 1.创建序列化对象
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    # 2.调用序列化器的loads进行解密
    try:
        access_token = serializer.loads(openid)
    except BadData:
        return None

    return access_token.get("openid")
